package smartlifev30.com.sdk.net.baiwei;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;


import java.util.HashMap;

import smartlifev30.com.sdk.BaseResponse;
import smartlifev30.com.sdk.ClientException;
import smartlifev30.com.sdk.util.JsonUtil;
import smartlifev30.com.sdk.StatusCode;


/**
 *
 * @author uesr
 * @date 2018/8/7
 */

public class ResponseHelper {

    /**
     * 装收到服务器应答后所有回调接口，通过MessageId确定对应关系
     */
    public final static HashMap<String, BaseResponseListen<?>> map = new HashMap<>(16);

    /**
     * 静态Handle, 用于线程切换
     */
    private static H h = new H(Looper.getMainLooper(), new HandleCallback());

    /**
     * 默认handle的What值，表示來自网络请求后或得的数据
     */
    public static final int DEFAULT_WHAT = 9999;

    public static void addListen(BaseResponseListen listen) {
        map.put(listen.msgId, listen);
    }

    static BaseResponseListen<?> removeListen(String msgId) {
       return map.remove(msgId);
    }

    public static boolean isContains(String msgId) {
        return map.containsKey(msgId);
    }

    /**
     * @param jsonStr 服务器返回的json字符串
     */
    public static void sendMessage(String jsonStr) {
        sendMessage(DEFAULT_WHAT, jsonStr);
    }

    static void post(Runnable r) {
        h.post(r);
    }

    private static void sendMessage(int what, String jsonStr) {
        switch (what) {
            case DEFAULT_WHAT: {
                BaseResponse baseResponse = JsonUtil.toObject(jsonStr, BaseResponse.class);
                String msgId = baseResponse.getMsg_id();
                if (map.containsKey(msgId)) {
                    Message message = h.obtainMessage(what, jsonStr);
                    Bundle data = new Bundle();
                    data.putString("msgId", msgId);
                    data.putInt("status", baseResponse.getStatus());
                    data.putInt("end", baseResponse.getEnd());
                    message.setData(data);
                    h.sendMessage(message);
                }else {
                    Log.e("0-0-", "map 中沒有:"+ msgId);
                }
            }
            break;
            default:
        }
    }

    static class H extends Handler {
        H(Looper looper, Callback callback) {
            super(looper, callback);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    private static class HandleCallback implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            boolean flag = true;
            switch (msg.what) {
                case DEFAULT_WHAT:
                    flag = ResponseHelper.handleResponse(msg);
                    break;
                default:
            }
            return flag;
        }
    }

    private static boolean handleResponse(Message msg) {
        Bundle data = msg.getData();
        String msgId = data.getString("msgId");
        int status = data.getInt("status");
        int end = data.getInt("end");
        String strObj = (String) msg.obj;
        BaseResponseListen listen = map.get(msgId);
        if (listen != null) {
            if (status == 0) {
                listen.onSuccess(msgId, strObj);
            } else {
                listen.onFailed(msgId, new ClientException(convertStatus(status), status), status);
            }
            if (end == 1) {
                removeListen(msgId);
            }
        }
        return true;
    }


    /**
     * 将错误码 转成对应的描述信息
     *
     * @param status
     * @return
     */
    private static String convertStatus(int status) {
        String result;
        switch (status) {
            case StatusCode.PHONE_IS_REG:
                result = "该手机号已经被注册";
                break;

            case StatusCode.NO_USER:
                result = "用户不存在";
                break;

            case StatusCode.PWD_ERROR:
                result = "密码错误";
                break;

            case StatusCode.TOKEN_OUT_TIME:
                result = "token过期";
                break;

            case StatusCode.TOKEN_NO_USE:
                result = "token无效";
                break;

            case StatusCode.CODE_NO_USE:
                result = "验证码无效";
                break;

            case StatusCode.GW_IS_BIND:
                result = "网关已被绑定";
                break;

            case StatusCode.NO_GW_MANAGER:
                result = "不是网关管理员";
                break;

            case StatusCode.USER_IS_IN_GW:
                result = "用户已经添加到指定网关";
                break;

            case StatusCode.GW_IS_NO_ONLINE:
                result = "指定的发送目标已经离线";
                break;

            case StatusCode.USER_OUT_TIME:
                result = "用户过期";
                break;

            case StatusCode.NORMAL_ERROR:
                result = "一般性错误";
                break;

            case StatusCode.CLASS_NULL:
                result = "对象为NULL";
                break;

            case StatusCode.DATA_PARSER_EXP:
                result = "数据包解析异常";
                break;

            case StatusCode.DATA_LEN_ERROR:
                result = "数据包长度错误";
                break;

            case StatusCode.GW_UPDATE_ERROR:
                result = "在线网关列表更新错误";
                break;

            case StatusCode.HEAD_DATA_ERROR:
                result = "包头输入参数有误";
                break;

            case StatusCode.PACKAGE_OUT_MAX_LEN:
                result = "包超过最大长度";
                break;

            case StatusCode.PACKAGE_NOT_COMPLETE:
                result = "包不完整";
                break;

            case StatusCode.MSG_CLASS_ERROR:
                result = "消息的类名不对";
                break;
            case StatusCode.MSG_NAME_ERROR:
                result = "消息的名无效";
                break;

            case StatusCode.URL_ERROR:
                result = "请求URL无效";
                break;

            case StatusCode.MSG_DOING_EXP:
                result = "消息处理过程中异常";
                break;

            case StatusCode.DATE_FORMAT_ERROR:
                result = "时间格式不正确";
                break;
            case StatusCode.START_MAX_STOP:
                result = "开始时间大于结束时间";
                break;

            case StatusCode.DB_EXP:
                result = "数据库操作异常";
                break;

            case StatusCode.DB_INFO_ZERO:
                result = "数据库操作记录数为0";
                break;

            case StatusCode.NUM_IS_NULL:
                result = "手机号或账号为空";
                break;

            case StatusCode.PASS_IS_NULL:
                result = "密码为空";
                break;

            case StatusCode.GW_CODE_ERROR:
                result = "网关code无效";
                break;

            case StatusCode.FROM_ERROR:
                result = "From参数无效";
                break;

            case StatusCode.GW_NO_USER:
                result = "用户在指定网关不存在";
                break;

            case StatusCode.ID_IS_OUTSIDE_LOGIN:
                result = "指定的客户端ID已经异地登录";
                break;

            case StatusCode.OBJ_IS_NULL:
                result = "指定的目标不存在";
                break;

            case StatusCode.NO_DELETE:
                result = "唯一的主用户不可以删除自己";
                break;

            case StatusCode.DEVICE_EXP:
                result = "操作指定的设备，异常";
                break;

            case StatusCode.MESSAGE_SEND_EXP:
                result = "短信发送异常";
                break;

            case StatusCode.MESSAGE_BACK_ERROR:
                result = "短信接口服务返回失败";
                break;

            case StatusCode.PUSH_NO_CHANNEL:
                result = "离线推送，客户端未上报参数 ChannelID";
                break;

            case StatusCode.PUSH_NO_REG_ID:
                result = "离线推送，客户端未上报参数 JPushRegId";
                break;

            case StatusCode.THIRD_PART_COMMON_ERROR:
                result = "第三方调用返回错误：一般错误";
                break;

            case StatusCode.THIRD_PART_PSW_LOGIN_FAIL:
                result = "第三方调用返回错误: 用户密码登录失败";
                break;

            case StatusCode.THIRD_PART_TOKEN_LOGIN_FAIL:
                result = "第三方调用返回错误: 用户Token登录失败";
                break;

            case StatusCode.SMS_BALANCE_OUT:
                result = "网关短信余额已经用光了";
                break;

            case StatusCode.NO_BIND_USER:
                result = "未绑定用户/用户不存在";
                break;

            case StatusCode.USER_PASS_ERROR:
                result = "用户密码错误";
                break;

            case StatusCode.TOKEN_NO_USER:
                result = "Token无效";
                break;

            case StatusCode.USER_NAME_HAVE:
                result = "用户名重复";
                break;

            case StatusCode.GW_IS_UNBIND:
                result = "家庭已被解散";
                break;

            case StatusCode.SCENE_NO_HAVE:
                result = "场景不存在/场景ID错误";
                break;

            case StatusCode.TIMER_NO_HAVE:
                result = "定时器不存在/定时ID错误";
                break;

            case StatusCode.ZONE_NO_HAVE:
                result = "防区不存在/防区ID错误";
                break;

            case StatusCode.DEVICE_OFFLINE:
                result = "设备离线";
                break;

            case StatusCode.DEVICE_NO_HAVE:
                result = "设备不存在/设备ID错误";
                break;

            case StatusCode.LINKAGE_NO_HAVE:
                result = "联动不存在/联动ID错误";
                break;

            case StatusCode.OUT_TIME:
                result = "响应超时";
                break;

            case StatusCode.IR_LEARN_OUT_TIME:
                result = "红外学习超时";
                break;

            case StatusCode.DEVICE_NO_TIME:
                result = "设备忙";
                break;

            case StatusCode.IR_CMD_SO_LEN:
                result = "红外命令过长";
                break;

            case StatusCode.BIT_TIME_SO_LEN:
                result = "位时间过长";
                break;

            case StatusCode.LOSE_MC:
                result = "丢失脉冲";
                break;

            case StatusCode.FLASH_IS_MAX:
                result = "Flash已满";
                break;

            case StatusCode.FLASH_IS_BAD:
                result = "Flash损坏";
                break;

            case StatusCode.IR_LEN_LOSE_MC:
                result = "红外命令过长，丢失脉冲";
                break;

            case StatusCode.NO_USE_IR_CMD:
                result = "非法的红外命令";
                break;

            case StatusCode.OPERATION_FAIL:
                result = "操作失败";
                break;

            case StatusCode.CODELIB_FILE_DOWNLOAD_FAIL:
                result = "红外码库文件下载失败";
                break;

            case StatusCode.PWD_FORMATION_ERRO:
                result = "密码格式不对";
                break;

            case StatusCode.DOORLOCK_USER_EXSITED:
                result = "门锁用户已存在";
                break;

            case StatusCode.DOORLOCK_ID_ILLEGAL:
                result = "门锁ID号非法";
                break;

            case StatusCode.DOORLOCK_PWD_EXSITED:
                result = "门锁密码已存在";
                break;

            case StatusCode.DOORLOCK_ID_TYPE_FULLED:
                result = "该类型门锁用户数已达上限";
                break;

            case StatusCode.DOORLOCK_PWD_ERROR:
                result = "门锁密码错误";
                break;

            case StatusCode.DOORLOCK_KEY_LOCKED:
                result = "门锁密码错误";
                break;

            case StatusCode.DOORLOCK_LOCKED:
                result = "门内已反锁";
                break;

            default:
                result = "未知错误";
        }
        return result;
    }

}
